import MediaGrid from "@/components/MediaGrid";
import { MaterialIcons } from "@expo/vector-icons";
import * as ImagePicker from "expo-image-picker";
import React, { useRef, useState } from "react";
import {
    Alert,
    ScrollView,
    StyleSheet,
    Text,
    TouchableOpacity,
    View,
} from "react-native";

interface MediaItem {
  id: string;
  uri: string;
  type: "photo" | "video" | "camera";
  duration?: number;
  creationTime: number;
  width?: number;
  height?: number;
}

interface PhotoSelectorProps {
  onImageSelect: (imageData: { source: string; width: number; height: number }) => void;
  onVideoSelect?: (videoData: { source: string; thumbnail: string; width: number; height: number }) => void;
}

export const PhotoSelector: React.FC<PhotoSelectorProps> = ({
  onImageSelect,
  onVideoSelect,
}) => {
  const [selectedItems, setSelectedItems] = useState<string[]>([]);
  const [filterType, setFilterType] = useState<"photo" | "video" | "all">("all");
  const mediaGridRef = useRef<any>(null);

  /**
   * 处理单选照片
   */
  const handleSingleSelect = (item: MediaItem) => {
    if (item.type === "camera") {
      handleTakePhoto();
      return;
    }

    if (item.type === "photo") {
      onImageSelect({
        source: item.uri,
        width: item.width || 200,
        height: item.height || 200,
      });
    } else if (item.type === "video" && onVideoSelect) {
      onVideoSelect({
        source: item.uri,
        thumbnail: item.uri, // 在实际应用中，这里应该是视频的缩略图
        width: item.width || 200,
        height: item.height || 200,
      });
    }
  };

  /**
   * 使用相机拍照
   */
  const handleTakePhoto = async () => {
    try {
      const { status } = await ImagePicker.requestCameraPermissionsAsync();
      if (status !== "granted") {
        Alert.alert("权限不足", "需要相机权限才能拍照");
        return;
      }

      const result = await ImagePicker.launchCameraAsync({
        mediaTypes: ImagePicker.MediaTypeOptions.Images,
        allowsEditing: false,
        quality: 0.8,
      });

      if (!result.canceled && result.assets[0]) {
        const asset = result.assets[0];
        onImageSelect({
          source: asset.uri,
          width: asset.width || 200,
          height: asset.height || 200,
        });
      }
    } catch (error) {
      console.error("拍照错误:", error);
      Alert.alert("错误", "拍照失败，请重试");
    }
  };

  /**
   * 处理媒体类型切换
   */
  const handleFilterChange = (type: "photo" | "video" | "all") => {
    setFilterType(type);
  };

  return (
    <View style={styles.container}>
      {/* 顶部切换栏 */}
      <View style={styles.filterContainer}>
        <ScrollView
          horizontal
          showsHorizontalScrollIndicator={false}
          contentContainerStyle={styles.filterScrollView}
        >
          <TouchableOpacity
            style={[
              styles.filterButton,
              filterType === "all" && styles.filterButtonActive,
            ]}
            onPress={() => handleFilterChange("all")}
          >
            <MaterialIcons 
              name="select-all" 
              size={20} 
              color={filterType === "all" ? "#007AFF" : "#666"} 
            />
            <Text
              style={[
                styles.filterText,
                filterType === "all" && styles.filterTextActive,
              ]}
            >
              全部
            </Text>
          </TouchableOpacity>
          
          <TouchableOpacity
            style={[
              styles.filterButton,
              filterType === "photo" && styles.filterButtonActive,
            ]}
            onPress={() => handleFilterChange("photo")}
          >
            <MaterialIcons 
              name="photo" 
              size={20} 
              color={filterType === "photo" ? "#007AFF" : "#666"} 
            />
            <Text
              style={[
                styles.filterText,
                filterType === "photo" && styles.filterTextActive,
              ]}
            >
              照片
            </Text>
          </TouchableOpacity>
          
          <TouchableOpacity
            style={[
              styles.filterButton,
              filterType === "video" && styles.filterButtonActive,
            ]}
            onPress={() => handleFilterChange("video")}
          >
            <MaterialIcons 
              name="videocam" 
              size={20} 
              color={filterType === "video" ? "#007AFF" : "#666"} 
            />
            <Text
              style={[
                styles.filterText,
                filterType === "video" && styles.filterTextActive,
              ]}
            >
              视频
            </Text>
          </TouchableOpacity>

          <TouchableOpacity
            style={styles.filterButton}
            onPress={handleTakePhoto}
          >
            <MaterialIcons name="photo-camera" size={20} color="#666" />
            <Text style={styles.filterText}>拍照</Text>
          </TouchableOpacity>
        </ScrollView>
      </View>

      {/* 媒体网格 */}
      <View style={styles.mediaContainer}>
        <MediaGrid
          ref={mediaGridRef}
          selectedItems={selectedItems}
          filterType={filterType}
          onItemPress={() => {}} // 不处理多选
          onCameraPress={handleTakePhoto}
          onFilterChange={setFilterType}
          onSingleSelect={handleSingleSelect}
          onMultipleSelect={() => {}} // 不处理多选
          mode="single"
        />
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    backgroundColor: 'f5f5f5',
    maxHeight: 200,
  },
  filterContainer: {
    backgroundColor: "#fff",
    borderBottomWidth: 1,
    borderBottomColor: "#e0e0e0",
    paddingVertical: 10,
  },
  filterScrollView: {
    paddingHorizontal: 20,
    alignItems: "center",
  },
  filterButton: {
    flexDirection: "row",
    alignItems: "center",
    paddingHorizontal: 16,
    paddingVertical: 8,
    marginRight: 12,
    borderRadius: 20,
    backgroundColor: "#f8f8f8",
  },
  filterButtonActive: {
    backgroundColor: "#e3f2fd",
  },
  filterText: {
    marginLeft: 6,
    fontSize: 14,
    color: "#666",
  },
  filterTextActive: {
    color: "#007AFF",
    fontWeight: "500",
  },
  mediaContainer: {
    // flex: 1,
  },
});
